package com.jinyang.jetpackdemo.livedata

import androidx.annotation.MainThread
import androidx.lifecycle.LiveData
import java.math.BigDecimal

/**
 * @Author: LiuJinYang
 * @CreateDate: 2021/8/10
 * @Description:
 */
class StockLiveData private constructor(symbol: String) : LiveData<BigDecimal?>() {
    private val stockManager: StockManager = StockManager(symbol)
    private val listener: SimplePriceListener = object : SimplePriceListener {
        override fun onPriceChanged(price: BigDecimal?) {
            value = price
        }
    }

    //活跃的观察者（LifecycleOwner）数量从 0 变为 1 时调用
    override fun onActive() {
        stockManager.requestPriceUpdates(listener) //开始观察股价更新
    }

    //活跃的观察者（LifecycleOwner）数量从 1 变为 0 时调用。
    //这不代表没有观察者了，可能是全都不活跃了。可以使用hasObservers()检查是否有观察者。
    override fun onInactive() {
        stockManager.removeUpdates(listener) //移除股价更新的观察
    }

    interface SimplePriceListener {
        fun onPriceChanged(price: BigDecimal?)
    }

    class StockManager(var symbol: String) {
        fun requestPriceUpdates(listener: SimplePriceListener?) {}
        fun removeUpdates(listener: SimplePriceListener?) {}
    }

    companion object {
        private var sInstance //单实例
                : StockLiveData? = null

        //获取单例
        @MainThread
        operator fun get(symbol: String): StockLiveData? {
            if (sInstance == null) {
                sInstance = StockLiveData(symbol)
            }
            return sInstance
        }
    }

}